'''
$LastChangedBy: csgillespie $
$LastChangedDate: 2007-06-06 11:08:06 +0000 (Wed, 06 Jun 2007) $
'''
import ConfigFile
import libsbml
CONFIG_VAR = ('username', 'password', 'model_urn', \
	'simulation_group_urn', 's_id', 'path')
PROTECTED = ('d')

class GlobalParameters(object):
	'''This class is inherited to allow variables such as model_urn to be accessed in a
	by allow classes'''
	def __init__(self, **kwargs):
		'''Create all variables'''
		
		if kwargs.get('base_values'):
			self.__setBaseValues(kwargs.pop('base_values'))
			
			for key, value in kwargs.items():
				setattr(self, key, value)
		else:
			ConfigFile.createConfigFile()
			config_dict = ConfigFile.getConfigFile()
			for value in CONFIG_VAR:
				if kwargs.has_key(value):
					setattr(self, value, kwargs[value])
					ConfigFile.addToConfigFile({value:kwargs[value]})
				else:
					setattr(self, value, config_dict[value])
		
	def __setBaseValues(self, kwarg):
		'''Each base_values attributes points to the orginal base_values'''
		if kwarg.__dict__.has_key('base_values'):
			kwarg = kwarg.__dict__['base_values']
			return self.__setBaseValues(kwarg)
		
		setattr(self, 'base_values', kwarg)
		
	
	def __setattr__(self, name, value):
		'''Only change the attributes of ConnectToBasis which are already there'''
		#Don't store an sbml attribute, just keep the libsbml one.
		if name == 'sbml':
			if value:
				d = libsbml.SBMLReader().readSBMLFromString(value)
			else:
				d = None
			if self.__dict__.has_key('base_values'):
				self.__dict__['base_values'].d = d
			else:
				self.__dict__['d'] = d
			return
		#If a global name change the config file
		if name in CONFIG_VAR:
			ConfigFile.addToConfigFile({name:value})
		if self.__dict__.has_key('base_values') and name in CONFIG_VAR:
			self.__dict__['base_values'].__dict__[name] = value
			return

		self.__dict__[name] = value
		
	def __getattribute__(self, name):
		if object.__getattribute__(self, '__dict__').has_key('base_values') \
			and (name in  PROTECTED or name in CONFIG_VAR):
			base_v = object.__getattribute__(self, '__dict__')['base_values']
			return base_v.__getattribute__(name)
		if name == 'sbml':
			if object.__getattribute__(self, '__dict__').has_key('base_values'):
				base_v = object.__getattribute__(self, '__dict__')['base_values']
				return base_v.__getattribute__('d').toSBML()
			else:
				return object.__getattribute__(self, 'd').toSBML()
		return object.__getattribute__(self, name)

	
if __name__ == '__main__':
	g = GlobalParameters()
	print g.model_urn, g.sdfsdf
